package cn.tk.service.mr.impl;

import cn.tk.model.pojo.mr.bot.ProductBot;
import cn.tk.service.mr.ProductBotService;
import cn.tk.utils.EmptyUtil;
import cn.tk.utils.JpaMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by denglw on 2021/8/10.<br/>
 * Desc: bot关联信息 服务实现层
 */
@Service
public class ProductBotServiceImpl implements ProductBotService {

    @Autowired
    private JpaMapper jpaMapper;

    @Override
    public List<ProductBot> getBots(String robotCode, String original) {
        StringBuilder sql = new StringBuilder();
        Map<String, Object> params = new HashMap<>(8);
        String originalSql = "select a.name, a.type, a.robot_id robotId, a.robot_code robotCode, a.product_id productId,\n" +
                "a.original, a.scene_id sceneId, b.code sceneCode, b.intent_id sceneIntentId, a.bot_id botId\n" +
                "from mr_product_bot_rel a, mr_scene b where a.scene_id=b.id\n" +
                "and a.original=:original and a.type=2 and b.deleted=0 and b.disabled=0";
        String robotCodeSql = "select a.name, a.type, a.robot_id robotId, a.robot_code robotCode, a.product_id productId,\n" +
                "a.original, a.scene_id sceneId, b.code sceneCode, b.intent_id sceneIntentId, a.bot_id botId\n" +
                "from mr_product_bot_rel a, mr_scene b where a.scene_id=b.id\n" +
                "and a.robot_code=:robotCode and a.type=1 and b.deleted=0 and b.disabled=0";
        if (EmptyUtil.allBlank(robotCode, original)) {
            return new ArrayList<>();
        }
        if (EmptyUtil.anyBlank(robotCode, original)) {
            if (EmptyUtil.nonBlank(robotCode)) {
                sql.append(robotCodeSql);
                params.put("robotCode", robotCode);
            }
            if (EmptyUtil.nonBlank(original)) {
                sql.append(originalSql);
                params.put("original", original);
            }
        }
        if (!EmptyUtil.anyBlank(robotCode, original)) {
            sql.append(robotCodeSql).append("\n union all \n").append(originalSql);
            params.put("robotCode", robotCode);
            params.put("original", original);
        }
        Class<?>[] clazzes = new Class[]{String.class, Integer.class, Long.class,
                String.class, Long.class, String.class, Long.class, String.class, Long.class, Long.class};
        return jpaMapper.queryList(sql.toString(), params, ProductBot.class, clazzes);
    }
}
